package com.creatorblue.config.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * security核心配置文件
 * @author zhuq
 *
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启方法安全级别的控制
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	
	/**
	 * 自定义加密策略
	 * @return
	 */
	@Bean
    public PasswordEncoder passwordEncoder() {
        return new Md5PasswordEncoder();
    }
	
	
	@Override
    protected void configure(HttpSecurity http) throws Exception {
    	
        http.formLogin()
                .loginPage("/login")// 自定义登录页面路径
                .loginProcessingUrl("/doLogin")// 自定义页面的登录路径，注意要与登录页面的action值一致，<form action="/authentication/form" method="post">，自已不要编写mvc方法处理该请求，由security处理
                .defaultSuccessUrl("/userinfo/list")//登陆成功后的跳转页面
                .failureHandler(new CBauthenticationFailureHandler())
                .and()
                .authorizeRequests() // 定义哪些URL需要被保护、哪些不需要被保护
                .antMatchers("/login", "/doLogin", "/ecode").permitAll()// 设置所有人都可以访问登录页面
                .anyRequest().authenticated()  // 除了以上的请求外都需要身份验证
        ;
        http.csrf().disable();// 禁用跨站攻击
        //将图形验证码校验的过滤器添加到账号密码校验过滤器之间
        http.addFilterBefore(new ValidateCodeFilter(), UsernamePasswordAuthenticationFilter.class);
    }
	
    
}
